<template>
  <el-drawer
    title="批量申请证书"
    class="basic-drawer detail-view"
    :model-value="visible"
    :size="800"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    @open="handleOpen"
    @closed="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      require-asterisk-position="right"
      label-width="100px"
      label-position="top"
      @submit.prevent
    >
      <el-form-item label="主域名" prop="domain">
        <el-input
          v-model="formState.domain"
          :rows="5"
          type="textarea"
          placeholder="请输入域名，一行一个，最多10个"
        />
      </el-form-item>

      <el-form-item label="备注" class="hide-star" prop="description">
        <el-input
          v-model.trim="formState.description"
          maxlength="20"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-form-item prop="acme_account_id" label="Acme 账户">
        <el-select
          v-model="formState.acme_account_id"
          v-loadmore="loadMore"
          :teleported="false"
          class="w-full"
        >
          <template #label="{ value, label }">
            <section class="flex items-center">
              <span>{{ label }} </span>
              <div
                class="px-2 bg-[#E8F3FF] text-[#165DFF] text-xs/5 rounded ml-[6px]"
              >
                {{
                  getOptionsLabel(
                    ACCOUNT_TYPE_OPTS,
                    acmeOpts.find(item => item.value === value)?.type
                  )
                }}
              </div>
            </section>
          </template>
          <el-option
            v-for="item in acmeOpts"
            :key="item.label"
            :label="item.label"
            :value="item.value"
            >{{ item.label }}
            <div
              class="px-2 bg-[#E8F3FF] text-[#165DFF] text-xs/5 rounded ml-[6px]"
            >
              {{ item.content }}
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="key_type" label="密钥算法">
        <el-select v-model="formState.key_type" class="w-full">
          <el-option
            v-for="item in ALGORITHM_OPTS"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="provider" label="验证方式">
        <el-radio-group v-model="formState.provider">
          <el-radio value="dns_account" label="dns_account">DNS账号</el-radio>
          <el-radio value="dns_manual" label="dns_manual" disabled
            >手动解析</el-radio
          >
        </el-radio-group>
      </el-form-item>
      <el-form-item prop="dns_account_id" label="DNS账号">
        <el-select
          v-model="formState.dns_account_id"
          v-loadmore="dnsLoadMore"
          :teleported="false"
          class="w-full"
        >
          <template #label="{ value, label }">
            <section class="flex items-center">
              <span>{{ label }} </span>
              <div
                class="px-2 bg-[#E8F3FF] text-[#165DFF] text-xs/5 rounded ml-[6px]"
              >
                {{
                  getOptionsLabel(
                    PROVIDER_TYPE,
                    dnsOpts.find(item => item.value === value)?.type!
                  )
                }}
              </div>
            </section>
          </template>
          <el-option
            v-for="item in dnsOpts"
            :key="item.label"
            :label="item.label"
            :value="item.value"
            >{{ item.label }}
            <div
              class="px-2 bg-[#E8F3FF] text-[#165DFF] text-xs/5 rounded ml-[6px]"
            >
              {{ item.content }}
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="auto_renew" label="">
        <el-checkbox v-model="formState.auto_renew">自动续签</el-checkbox>
      </el-form-item>
      <el-form-item label="DNS服务器1" class="hide-star" prop="server1">
        <el-input
          v-model.trim="formState.server1"
          maxlength="20"
          placeholder="使用自定义的 DNS 服务器来校验域名"
        />
      </el-form-item>
      <el-form-item label="DNS服务器2" class="hide-star" prop="server2">
        <el-input
          v-model.trim="formState.server2"
          maxlength="20"
          placeholder="使用自定义的 DNS 服务器来校验域名"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <section class="flex justify-end">
        <el-button @click="emit('update:visible', false)">返回</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确认
        </el-button>
      </section>
    </template>
  </el-drawer>
</template>
<script lang="ts" setup>
// import type { NoticeListReturn } from '@/apis/model/notice'
import type { FormInstance, FormItemRule } from 'element-plus'

import { ACCOUNT_TYPE_OPTS, ALGORITHM_OPTS } from '@/config/constant/cert'
import { PROVIDER_TYPE } from '@/config/constant/dns'
interface IProps {
  visible: boolean
  loading?: boolean
  id?: string
}
withDefaults(defineProps<IProps>(), {
  visible: false,
  loading: false
})
// 刷新表格事件
interface IEmit {
  (event: 'update:visible', value: boolean): void
  (event: 'update:loading', value: boolean): void
  (event: 'refresh'): void
}
const emit = defineEmits<IEmit>()
const formRef = ref<FormInstance>()
const acmeOpts = ref<{ label: string; value: string; content: string }[]>([])
const dnsOpts = ref<{ label: string; value: string; content: string }[]>([])
const formState = reactive({
  acme_account_id: '',
  auto_renew: true,
  description: '',
  dns_account_id: '',
  domain: '',
  domain_list: [],
  key_type: 'P256',
  nameserver_list: [],
  provider: 'dns_account',
  server1: '',
  server2: ''
})

const validateDomain = (_rule: any, value: any, callback: any) => {
  if (!value) return callback()
  const valueList = value.split('\n').filter(Boolean)
  const num = valueList.length
  let isOut
  valueList.map((item: string) => {
    item = item.trim()
    if (item.length > 100) {
      return new Error('域名总长度不能超过100个字符')
    }
    if (item.startsWith('*.')) {
      item = item.substring(2, item.length - 1)
    }
    if (!wildcardDomainReg.test(item)) isOut = true
  })
  if (isOut) {
    callback(new Error('域名格式不正确'))
  } else if (num > 10) {
    callback(new Error('已超过配置上限，请核对'))
  } else {
    callback()
  }
}
const rules: Record<string, FormItemRule[]> = {
  domain: [
    { required: true, message: '请输入域名', trigger: 'blur' },
    {
      validator: validateDomain
    }
  ],
  acme_account_id: [{ required: true, message: '请选择', trigger: 'change' }],
  key_type: [{ required: true, message: '请选择', trigger: 'change' }],
  provider: [{ required: true, message: '请选择', trigger: 'change' }]
}

const pageData = reactive({
  offset: 0,
  limit: 10
})
const getAcmeOpts = () => {
  getAcmeApi({
    order: 'asc',
    sort: 'created_at',
    ...pageData
  }).then((res: any) => {
    if (res.list.length < 1) {
      ToastUtils.warning('没有更多数据了...')
    }
    formState.acme_account_id = res.list[0].id
    const newOptions = res.list.map((item: any) => {
      return {
        value: item.id,
        label: item.email,
        type: item.type,
        content: getOptionsLabel(ACCOUNT_TYPE_OPTS, item.type)
      }
    })
    acmeOpts.value.push(...newOptions)
  })
}

// 触底了，继续发请求
const loadMore = async () => {
  pageData.offset = pageData.offset + 1
  await getAcmeOpts()
}

const dnsPageData = reactive({
  offset: 0,
  limit: 10
})
const getDnsOpts = () => {
  getDnsApi({
    order: 'asc',
    sort: 'created_at',
    ...dnsPageData
  }).then((res: any) => {
    if (res.list.length < 1) {
      ToastUtils.warning('没有更多数据了...')
    }
    formState.dns_account_id = res.list[0].id
    const newOptions = res.list.map((item: any) => {
      return {
        value: item.id,
        label: item.name,
        type: item.type,
        content: getOptionsLabel(PROVIDER_TYPE, item.type)
      }
    })
    dnsOpts.value.push(...newOptions)
  })
}
const dnsLoadMore = async () => {
  dnsPageData.offset = dnsPageData.offset + 1
  await getDnsOpts()
}
//弹窗打开
const handleOpen = () => {
  getAcmeOpts()
  getDnsOpts()
}

async function handleSubmit() {
  await formRef.value?.validate()
  const params = { ...formState } as any
  params.domain_list = params.domain.split('\n').filter(Boolean) || []
  params.nameserver_list = [params.server1, params.server2].filter(Boolean)
  emit('update:loading', true)
  batchCreateCertApi(params)
    .then(() => {
      ToastUtils.success('操作成功')
      handleClose()
      emit('refresh')
    })
    .finally(() => emit('update:loading', false))
}
//弹窗关闭
const handleClose = () => {
  dnsOpts.value = []
  acmeOpts.value = []
  formRef.value?.resetFields()
  emit('update:visible', false)
}
</script>

<style lang="scss" scoped>
.detail-view {
  .detail-title {
    border-bottom: 1px solid #edeef0;
    @apply pb-4;
  }

  .detail-body {
    @apply pt-4 leading-[22px];
    align-self: stretch;
  }
}
</style>
